package io.renren.modules.lucky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.constants.ListConstants;
import io.renren.modules.app.constants.StringConstants;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.lucky.dao.AppSysOpertionDao;
import io.renren.modules.lucky.entity.AppSysOpertionEntity;
import io.renren.modules.lucky.service.AppSysOpertionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service("appSysOpertionService")
public class AppSysOpertionServiceImpl extends ServiceImpl<AppSysOpertionDao, AppSysOpertionEntity>
        implements AppSysOpertionService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AppSysOpertionDao appSysOpertionDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AppSysOpertionEntity> page = this.page(
                new Query<AppSysOpertionEntity>().getPage(params), new QueryWrapper<AppSysOpertionEntity>()
        );
        return new PageUtils(page);
    }

    @Transactional(readOnly = false)
    public int addAnalyseInfo(String userId, String operationCode, String operationName, String token){
        if(jwtUtils.getClaimByToken(token)==null)
            throw new RRException("token已失效，请重新登录");
        String id = jwtUtils.getClaimByToken(token).getSubject();
        if(id.equals(userId)) {
            //获取1-100的随机整数
            int num = new Random().nextInt(100)+1;
            if(num<= StringConstants.filterNum) {
                AppSysOpertionEntity opertion = new AppSysOpertionEntity();
                opertion.setCreateTime(new Date());
                opertion.setOperationCode(operationCode);
                opertion.setOperationName(operationName);
                opertion.setOperationType("1");
                opertion.setUserId(Integer.parseInt(userId));
                //加入缓存中
                ListConstants.analyseList.add(opertion);
                if (ListConstants.analyseList.size() > 99) {
                    //进行批量插入操作，执行100条操作的插入
                    boolean boo = appSysOpertionDao.insertBatch(ListConstants.analyseList);
                    if(boo)
                        ListConstants.analyseList.clear();
                }
            }
            return ListConstants.analyseList.size();
        }else{
            throw new RRException("请求用户id与token不匹配");
        }
    }

}